package com.adxon.servlet;

import com.adxon.cookie.Station;
import com.adxon.data.Item;
import com.adxon.data.Picture;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class UploadServlet extends ServletBase{
	private String jsp;

	public void init()throws ServletException{
		super.init();
		jsp=getInitParameter("jsp-file");
		if(jsp==null)
			jsp="std-article.jsp";
	}
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException{
		setAttributes(req,"Upload");
		req.setAttribute("Article",
				"<form class=std method=post enctype=multipart/form-data>"+
				"<input type=file name=f class=file>"+
				"<input type=submit value=Upload id=submit>"+
				"</form>");
		forward(jsp,jsp,req,resp);
	}
	public void doPost(HttpServletRequest req,HttpServletResponse resp)
			throws IOException, ServletException{
		try{
			FileItemIterator t=new ServletFileUpload().getItemIterator(req);
			while(t.hasNext()){
				FileItemStream i=t.next();
				if (!i.isFormField()){
					Picture b=new Picture();
					Item u=Station.getCurrentUser(req);
					if(u!=null){
						b.setOwner(u);
						b.setRate(60);
					}
					b.setBits(i.openStream());
					b.setContentType(i.getContentType());
					b.setMaxSize(getInitParameter("max-size"));
					b.setRatio(getInitParameter("ratio"));
					b.commit();
					resp.setContentType("text/plain");
					resp.sendRedirect('/'+b.getPermaLink()+".htm");
					//System.out.println("Uploaded: "+i.getFieldName()+", "+i.getName());
				}
			}
		}catch(Exception ex){
			throw new ServletException(ex);
		}
	}
}